import { ElMessage } from 'element-plus';

// 获取 JSESSIONID
export const getJSessionId = () => {
    // 尝试从 localStorage 获取 JSESSIONID
    const jsessionId = localStorage.getItem('JSESSIONID');

    if (!jsessionId) {
        ElMessage.error('JSESSIONID 未找到');
        return null;
    }
    return jsessionId;
};

// 连接 WebSocket
export const connectWebSocket = (ws, route, setMessages, heartbeatInterval = 30000, reconnectInterval = 5000) => {
    const jsessionId = getJSessionId();
    if (!jsessionId) return;

    // 创建 WebSocket 连接
    ws.value = new WebSocket('ws://10.33.16.198:18080/disputes/chat');

    // 在 WebSocket 连接建立时，发送 JSESSIONID
    ws.value.onopen = () => {
        console.log('WebSocket 连接成功');

        // 发送心跳
        setInterval(() => {
            if (ws.value && ws.value.readyState === WebSocket.OPEN) {
                ws.value.send(JSON.stringify({ type: 'heartbeat' }));
            }
        }, heartbeatInterval);

        // 发送登录请求，携带JSESSIONID
        const payload = {
            type: 'login',
            jsessionId,
        };
        ws.value.send(JSON.stringify(payload));
    };

    // 处理消息
    ws.value.onmessage = (event) => {
        const data = JSON.parse(event.data);
        if (data.type === 'chat') {
            setMessages(prevMessages => [...prevMessages, {
                id: data.id,
                senderName: data.senderName,
                content: data.content,
            }]);
        } else if (data.type === 'system') {
            ElMessage.success(data.content);
        }
    };

    // 处理 WebSocket 错误
    ws.value.onerror = (error) => {
        console.error('WebSocket 错误', error);
        setTimeout(() => connectWebSocket(ws, route, setMessages), reconnectInterval);
    };

    // 处理 WebSocket 关闭
    ws.value.onclose = () => {
        console.log('WebSocket 连接关闭，尝试重新连接...');
        setTimeout(() => connectWebSocket(ws, route, setMessages), reconnectInterval);
    };
};

// 发送消息
export const sendMessage = (ws, message, route) => {
    if (message.trim() === '') {
        ElMessage.warning('请输入消息');
        return;
    }

    if (!ws.value || ws.value.readyState !== WebSocket.OPEN) {
        ElMessage.warning('WebSocket 未连接');
        return;
    }

    const payload = {
        type: 'chat',
        receiverId: route.query.receiverId,
        orderId: route.query.orderId,
        senderId: route.query.senderId,
        content: message,
        imageUrl: null,
    };

    ws.value.send(JSON.stringify(payload));
};

// 获取聊天历史
export const fetchChatHistory = async (orderId, firId, secId, setMessages) => {
    try {
        const response = await fetch(`http://10.34.62.73:18080/disputes/${orderId}/${firId}/${secId}/history`, {
            method: 'GET',
            headers: {
                'Content-Type': 'application/json',
            },
        });

        if (!response.ok) {
            throw new Error(`请求失败，状态码：${response.status}`);
        }

        const data = await response.json();
        if (data.success) {
            setMessages(data.history);
        } else {
            alert('加载历史记录失败');
        }
    } catch (error) {
        console.error('获取聊天历史记录失败', error);
        alert('获取历史记录失败');
    }
};

// 提起纠纷
export const submitDispute = async (disputeId, ws) => {
    const payload = {
        type: 'DISPUTE',
        disputeId,
    };
    ws.value.send(JSON.stringify(payload));
};
